#include "global.h"


MySqlPool g_mysqlPool;
QMap<QString ,QStringList > g_dnSuffixMappingWhoIs;
int g_undefineCategoryId;//未分类域名的ID
ProxyPool g_proxyPool;
QQueue<std::unique_ptr<CTClientSocket>*> g_dnQueue;
QMutex  g_dnQueueMutex;
bool g_enableProxy;
int g_currentDealNum;
DataDict g_testProxyDest;
QVector<DataDict > g_dataDicts;
// Global::Global()
// {

// }
QMap<QString, QString> g_decodeWhoisInfoToMap(int dnType, QByteArray data)
{
    //    QString suffix = dnStr.section('.',1,-1);
    QString separator,bufStr;
    QMap<QString, QString> infoMaps;
    bufStr = data;
    //qDebug()<<suffix;
    //    QStringList strWhois = g_dnSuffixMappingWhoIs["."+suffix];
    //    if(strWhois.size()==0)
    //    {
    //        qDebug()<<"无法查找到匹配的域名服务器!"<<dnStr;
    //        return infoMaps;
    //    }
    //清除DNSSEC: unsigned之后的无效数据
    int index = bufStr.indexOf("DNSSEC");
    if(index==-1)
    {
        qDebug()<<"域名未注册,没有DNSSEC信息.";
        infoMaps["Regist Status"]="未注册";
    }
    else
    {
        //    if (index >= 0)//把DNSSEC: unsigned内容包进来
        //        bufStr = bufStr.left(index+16);

        if(dnType==1)
            separator = "\r\n";
        else
            separator = "\n";
        //qDebug()<<bufStr;
        QStringList domainStrings = bufStr.split(separator);

        //QVector<QString> statusVectors, nameServerVectors;
        QString sv,nsv;
        QString keystr, valstr;

        for (int i = 0; i < domainStrings.size(); i++) {
            //qDebug()<<domainStrings.at(i);

            QStringList infoStrings = domainStrings.at(i).split(": ");
            if(infoStrings.size()<1)
            {
                qDebug() << "接收数据异常: " << domainStrings.at(i);
                infoMaps.clear();
                return infoMaps;
            }
            keystr = infoStrings.at(0).trimmed();
            if(infoStrings.size()==2)
                valstr = infoStrings.at(1).left(127);
            else
                valstr="";
            if(valstr=="REDACTED FOR PRIVACY"||valstr.contains("Please query the WHOIS"))
                valstr="";

            if (keystr == "Domain Status") {
                //statusVectors.append(valstr);
                QStringList astr = valstr.split(" ");
                sv+=astr.at(0);
                sv+=";";
                infoMaps[keystr]=sv;
            } else if (keystr == "Name Server") {
                //nameServerVectors.append(valstr);
                nsv+=valstr;
                nsv+=";";
                infoMaps[keystr]=nsv;
            } else {
                infoMaps[keystr] = valstr;
            }
            //qDebug() << keystr << valstr;
            if (keystr.trimmed() == "DNSSEC")
                break;
        }
        //qDebug() << "成功接收数据" << infoMaps.size()<<dnStr;//<<infoMaps;
        infoMaps["Regist Status"]="已注册";
    }
    return infoMaps;
}

DomainInfo g_ParseBytesToDomainInfo(QByteArray data, QString reqParam,int domainId)
{
    DomainInfo dnInfo;
    //qDebug()<<__FUNCTION__<<QThread::currentThreadId()<<"ParseBytesToDomainInfo"<<reqParam<<data.length();//<<data;
    if(data.length()==0)
    {
        qDebug()<<"查询异常!"<<reqParam;
        dnInfo.Domain="";
        return dnInfo;
    }

    QMap<QString, QString> infoMaps;
    QString suffix = "."+reqParam.section('.',1,-1);
    QStringList strWhois = g_dnSuffixMappingWhoIs[suffix];
    if(strWhois.size()==0)
    {
        qDebug()<<"无法查找到匹配的域名服务器!"<<reqParam;
        dnInfo.Domain="";
        return dnInfo;
    }
    int dnType = strWhois.at(2).toInt();

    infoMaps = g_decodeWhoisInfoToMap(dnType,data);
    if(infoMaps.size()==0)
    {
        qDebug()<<"域名查询返回数据解析失败"<<reqParam<<data;
        dnInfo.Domain="";
        return dnInfo;
    }


    if(dnType==1)//以/r/n分行
    {
        dnInfo.Id=domainId;
        dnInfo.CategoryId=domainId;
        dnInfo.Domain=infoMaps["Domain Name"];
        dnInfo.Suffix=suffix;
        dnInfo.RegistStatus = infoMaps["Regist Status"];
        dnInfo.RegistryDomainID=infoMaps["Registry Domain ID"];
        dnInfo.RegistrarWHOISServer=infoMaps["Registrar WHOIS Server"];
        dnInfo.RegistrarURL=infoMaps["Registrar URL"];
        dnInfo.UpdatedDate=infoMaps["Updated Date"];
        dnInfo.CreationDate=infoMaps["Creation Date"];
        dnInfo.RegistryExpiryDate=infoMaps["Registry Expiry Date"];
        dnInfo.Registrar=infoMaps["Registrar"];
        dnInfo.RegistrarIANAID=infoMaps["Registrar IANA ID"];
        dnInfo.RegistrarEmail=infoMaps["Registrar Abuse Contact Email"];
        dnInfo.RegistrarPhone=infoMaps["Registrar Abuse Contact Phone"];
        dnInfo.RegistryRegistrantID=infoMaps["Registry Registrant ID"];
        dnInfo.RegistrantName=infoMaps["Registrant Name"];
        dnInfo.RegistrantOrganization=infoMaps["Registrant Organization"];
        dnInfo.RegistrantStreet=infoMaps["Registrant Street"];
        dnInfo.RegistrantCity=infoMaps["Registrant City"];
        dnInfo.RegistrantStateProvince=infoMaps["Registrant State/Province"];
        dnInfo.RegistrantPostalCode=infoMaps["Registrant Postal Code"];
        dnInfo.RegistrantCountry=infoMaps["Registrant Country"];
        dnInfo.RegistrantPhone=infoMaps["Registrant Phone"];
        dnInfo.RegistrantFax=infoMaps["Registrant Fax"];
        dnInfo.RegistrantEmail=infoMaps["Registrant Email"];
        dnInfo.NameServer=infoMaps["Name Server"];
        dnInfo.DomainStatus=infoMaps["Domain Status"];
        dnInfo.DNSSEC=infoMaps["DNSSEC"];
    }
    else//以/n分行
    {

        dnInfo.Id=domainId;
        dnInfo.CategoryId=domainId;
        dnInfo.Domain=infoMaps["Domain Name"];
        dnInfo.Suffix=suffix;
        dnInfo.RegistStatus = infoMaps["Regist Status"];
        dnInfo.RegistryDomainID=infoMaps["Registry Domain ID"];
        dnInfo.RegistrarWHOISServer=infoMaps["Registrar WHOIS Server"];
        dnInfo.RegistrarURL=infoMaps["Registrar URL"];
        dnInfo.UpdatedDate=infoMaps["Registration Time"];
        dnInfo.CreationDate=infoMaps["Registration Time"];
        dnInfo.RegistryExpiryDate=infoMaps["Expiration Time"];
        dnInfo.Registrar=infoMaps["Sponsoring Registrar"];
        dnInfo.RegistrarIANAID=infoMaps["Registrar IANA ID"];
        dnInfo.RegistrarEmail=infoMaps["Registrar Abuse Contact Email"];
        dnInfo.RegistrarPhone=infoMaps["Registrar Abuse Contact Phone"];
        dnInfo.RegistryRegistrantID=infoMaps["Registry Registrant ID"];
        dnInfo.RegistrantName=infoMaps["Registrant"];
        dnInfo.RegistrantOrganization=infoMaps["Registrant Organization"];
        dnInfo.RegistrantStreet=infoMaps["Registrant Street"];
        dnInfo.RegistrantCity=infoMaps["Registrant City"];
        dnInfo.RegistrantStateProvince=infoMaps["Registrant State/Province"];
        dnInfo.RegistrantPostalCode=infoMaps["Registrant Postal Code"];
        dnInfo.RegistrantCountry=infoMaps["Registrant Country"];
        dnInfo.RegistrantPhone=infoMaps["Registrant Phone"];
        dnInfo.RegistrantFax=infoMaps["Registrant Fax"];
        dnInfo.RegistrantEmail=infoMaps["Registrant Email"];
        dnInfo.NameServer=infoMaps["Registrar"];
        dnInfo.DomainStatus=infoMaps["Name Server"];
        dnInfo.DNSSEC=infoMaps["DNSSEC"];

    }
    QDate currentDate = QDate::currentDate();
    dnInfo.LastQryDate = currentDate.toString("yyyy-MM-dd");
    return dnInfo;
}

bool g_updateDomainDetailInfoById(int domainId, QString domainName, DomainInfo dnInfo)
{
    QSqlDatabase m_db = g_mysqlPool.getConnection();
    QSqlQuery query(m_db);
    query.prepare("update domain_registry_info set DomainSuffix=?, RegistStatus=?,RegistryDomainID=?,RegistrarWHOISServer=?,RegistrarURL=?,UpdatedDate=?,CreationDate=?,RegistryExpiryDate=?,Registrar=?,RegistrarIANAID=?,RegistrarEmail=?,RegistrarPhone=?,RegistryRegistrantID=?,RegistrantName=?,RegistrantOrganization=?,RegistrantStreet=?,RegistrantCity=?,RegistrantStateProvince=?,RegistrantPostalCode=?,RegistrantCountry=?,RegistrantPhone=?,RegistrantFax=?,RegistrantEmail=?,NameServer=?,DomainStatus=?,DNSSEC=?,LastQryDate=?  where id =?");

    query.addBindValue(dnInfo.Suffix);
    query.addBindValue(dnInfo.RegistStatus);
    query.addBindValue(dnInfo.RegistryDomainID);
    query.addBindValue(dnInfo.RegistrarWHOISServer);
    query.addBindValue(dnInfo.RegistrarURL);
    query.addBindValue(dnInfo.UpdatedDate.left(10));
    query.addBindValue(dnInfo.CreationDate.left(10));
    query.addBindValue(dnInfo.RegistryExpiryDate.left(10));
    query.addBindValue(dnInfo.Registrar);
    query.addBindValue(dnInfo.RegistrarIANAID);
    query.addBindValue(dnInfo.RegistrarEmail);
    query.addBindValue(dnInfo.RegistrarPhone);
    query.addBindValue(dnInfo.RegistryRegistrantID);
    query.addBindValue(dnInfo.RegistrantName);
    query.addBindValue(dnInfo.RegistrantOrganization);
    query.addBindValue(dnInfo.RegistrantStreet);
    query.addBindValue(dnInfo.RegistrantCity);
    query.addBindValue(dnInfo.RegistrantStateProvince);
    query.addBindValue(dnInfo.RegistrantPostalCode);
    query.addBindValue(dnInfo.RegistrantCountry);
    query.addBindValue(dnInfo.RegistrantPhone);
    query.addBindValue(dnInfo.RegistrantFax);
    query.addBindValue(dnInfo.RegistrantEmail);
    query.addBindValue(dnInfo.NameServer);
    query.addBindValue(dnInfo.DomainStatus);
    query.addBindValue(dnInfo.DNSSEC);
    query.addBindValue(dnInfo.LastQryDate);
    query.addBindValue(domainId);

    if (!query.exec())
    {
        qDebug() << "Failed to updateDomainRegistryInfo: " << query.lastError().text();
        g_mysqlPool.releaseConnection(m_db);
        return false;
    }
    g_mysqlPool.releaseConnection(m_db);
    //qDebug()<<"updateDomainRegistryInfo success"<<domainId<<domainName<<dnInfo.Registrar;
    return true;
}

bool g_updateDomainDetailInfoByIdToSqlite(DomainInfo dnInfo,QSqlDatabase db)
{
    QSqlDatabase m_db = db;
    QSqlQuery query(m_db);
    query.prepare("update domain_registry_info set DomainSuffix=?, RegistStatus=?,RegistryDomainID=?,RegistrarWHOISServer=?,RegistrarURL=?,UpdatedDate=?,CreationDate=?,RegistryExpiryDate=?,Registrar=?,RegistrarIANAID=?,RegistrarEmail=?,RegistrarPhone=?,RegistryRegistrantID=?,RegistrantName=?,RegistrantOrganization=?,RegistrantStreet=?,RegistrantCity=?,RegistrantStateProvince=?,RegistrantPostalCode=?,RegistrantCountry=?,RegistrantPhone=?,RegistrantFax=?,RegistrantEmail=?,NameServer=?,DomainStatus=?,DNSSEC=?,LastQryDate=?  where id =?");

    query.addBindValue(dnInfo.Suffix);
    query.addBindValue(dnInfo.RegistStatus);
    query.addBindValue(dnInfo.RegistryDomainID);
    query.addBindValue(dnInfo.RegistrarWHOISServer);
    query.addBindValue(dnInfo.RegistrarURL);
    query.addBindValue(dnInfo.UpdatedDate.left(10));
    query.addBindValue(dnInfo.CreationDate.left(10));
    query.addBindValue(dnInfo.RegistryExpiryDate.left(10));
    query.addBindValue(dnInfo.Registrar);
    query.addBindValue(dnInfo.RegistrarIANAID);
    query.addBindValue(dnInfo.RegistrarEmail);
    query.addBindValue(dnInfo.RegistrarPhone);
    query.addBindValue(dnInfo.RegistryRegistrantID);
    query.addBindValue(dnInfo.RegistrantName);
    query.addBindValue(dnInfo.RegistrantOrganization);
    query.addBindValue(dnInfo.RegistrantStreet);
    query.addBindValue(dnInfo.RegistrantCity);
    query.addBindValue(dnInfo.RegistrantStateProvince);
    query.addBindValue(dnInfo.RegistrantPostalCode);
    query.addBindValue(dnInfo.RegistrantCountry);
    query.addBindValue(dnInfo.RegistrantPhone);
    query.addBindValue(dnInfo.RegistrantFax);
    query.addBindValue(dnInfo.RegistrantEmail);
    query.addBindValue(dnInfo.NameServer);
    query.addBindValue(dnInfo.DomainStatus);
    query.addBindValue(dnInfo.DNSSEC);
    query.addBindValue(dnInfo.LastQryDate);
    query.addBindValue(dnInfo.Id);

    if (!query.exec())
    {
        qDebug() << "Failed to g_updateDomainDetailInfoByIdToSqlite: " << query.lastError().text();
        return false;
    }
    //qDebug()<<"updateDomainRegistryInfo success"<<domainId<<domainName<<dnInfo.Registrar;
    return true;
}
